<?php

namespace App\Http\Controllers\Api;

use App\Activity;
use App\AnswerSheet;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Questions;
use App\User;
use App\UserAnswer;
use App\UserAnswerDetail;
use App\UserInfo;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AnswerSheetController extends Controller
{
    public function getAnswerSheetList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 1;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动不存在']);

        /** @var AnswerSheet $answerSheet */
        $answerSheetList = AnswerSheet::whereActivityId($activityId)->whereStatus(1)->orderBy('sort','asc')->get();
        if(count($answerSheetList) . 0){
            foreach($answerSheetList as $answerSheet){
                if($answerSheet->sort == 1){
                    $answerSheet->sort_name = "第一轮";
                }elseif($answerSheet->sort == 2){
                    $answerSheet->sort_name = "第二轮";
                }

                $answerNum = UserAnswer::whereAsId($answerSheet->id)->count();
                $answerSheet->answer_num = $answerNum;
                $answerSheet->user_fraction = '';
                if(strtotime($answerSheet->start_time) > time()){
                    $answerSheet->user_status = -1;
                    $answerSheet->user_answer_status = '未开始';
                }elseif(strtotime($answerSheet->start_time) <= time() && strtotime($answerSheet->end_time) > time()){
                    $answerSheet->user_status = 0;
                    $answerSheet->user_answer_status = '去回答';
                }elseif(strtotime($answerSheet->end_time) <= time()){
                    $answerSheet->user_status = -1;
                    $answerSheet->user_answer_status = '已结束';
                }

                if($user){
                    if($answerSheet->sort == 2){
                        /** @var AnswerSheet $answerSheetOne */
                        $answerSheetOne = AnswerSheet::whereSort(1)->whereStatus(1)->first();
                        if($answerSheetOne){
                            $UserAnswerOne = UserAnswer::whereAsId($answerSheetOne->id)->whereStatus(2)->orderBy('score','desc')->orderBy('submit_time','asc')->take(30)->pluck('user_id')->toArray();
                            if(!in_array($user->id,$UserAnswerOne)){
                                $answerSheet->user_status = 10;
                            }
                        }
                    }

                    /** @var UserAnswer $userAnswer */
                    $userAnswer = UserAnswer::whereUserId($user->id)->whereAsId($answerSheet->id)->first();
                    if($userAnswer){
                        if($userAnswer->status == 2){
                            $answerSheet->user_fraction = $userAnswer->score;
                        }else{
                            $answerSheet->user_fraction = '';
                        }

                        if($userAnswer->status == 0){
                            $answerSheet->user_status = 0;
                            $answerSheet->user_answer_status = '去回答';
                        }elseif($userAnswer->status == 1){
                            $answerSheet->user_status = 1;
                            $answerSheet->user_answer_status = '评分中';
                        }elseif($userAnswer->status == 2){
                            $userAnswer = UserAnswer::whereAsId($answerSheet->id)->whereStatus(1)->count();
                            $userAnswerScore = UserAnswer::whereAsId($answerSheet->id)->whereStatus(2)->count();

                            if($userAnswer != $userAnswerScore){
                                $answerSheet->user_status = 2;
                                $answerSheet->user_answer_status = '已评分';
                            }

                            if(strtotime($answerSheet->end_time) <= time() && $userAnswer == $userAnswerScore){
                                if($answerSheet->sort == 1){
                                    $UserAnswerOne = UserAnswer::whereAsId($answerSheet->id)->orderBy('score','desc')->orderBy('submit_time','asc')->take(30)->pluck('user_id')->toArray();
                                    if(in_array($user->id,$UserAnswerOne)){
                                        $answerSheet->user_status = 3;
                                        $answerSheet->user_answer_status = '已过关';
                                    }else{
                                        $answerSheet->user_status = 4;
                                        $answerSheet->user_answer_status = '已淘汰';
                                    }
                                }elseif($answerSheet->sort == 2){
                                    $UserAnswerOne = UserAnswer::whereAsId($answerSheet->id)->orderBy('score','desc')->orderBy('submit_time','asc')->take(3)->pluck('user_id')->toArray();
                                    if(in_array($user->id,$UserAnswerOne)){
                                        $answerSheet->user_status = 3;
                                        $answerSheet->user_answer_status = '已过关';
                                    }else{
                                        $answerSheet->user_status = 4;
                                        $answerSheet->user_answer_status = '已淘汰';
                                    }
                                }
                            }
                        }else{
                            $answerSheet->user_answer_status = '未知';
                        }
                    }
                }
            }
        }

        $answerImg = FileManager::getImgUrl($thisActivity->img_id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $answerSheetList,'answer_img' => $answerImg]);
    }

    public function getQuestionsList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        $answerSheetId = !is_null($request->get('answer_sheet_id')) ? $request->get('answer_sheet_id') : 1;

        $answerSheetTitle = '';

        /** @var AnswerSheet $answerSheet */
        $answerSheet = AnswerSheet::whereId($answerSheetId)->whereStatus(1)->first();
        if($answerSheet){
            $answerSheetTitle = $answerSheet->title;
        }

        /** @var Questions $questions */
        $questionsList = Questions::whereAsId($answerSheetId)->whereStatus(1)->orderBy('sort','asc')->get();
        if(count($questionsList) > 0){
            foreach($questionsList as $questions){
                $questions->answer_sheet_end_time = '';

                /** @var AnswerSheet $answerSheet */
                $answerSheet = AnswerSheet::whereId($questions->as_id)->whereStatus(1)->first();
                if($answerSheet){
                    $questions->answer_sheet_end_time = $answerSheet->end_time;
                }

                $questions->user_answer = '';

                if($user){
                    /** @var UserAnswer $userAnswer */
                    $userAnswer = UserAnswer::whereUserId($user->id)->first();
                    if($userAnswer){
                        /** @var UserAnswerDetail $userAnswerDetail */
                        $userAnswerDetail = UserAnswerDetail::whereUaId($userAnswer->id)->whereQId($questions->id)->first();
                        if($userAnswerDetail){
                            $questions->user_answer = $userAnswerDetail->answer;
                        }
                    }
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $questionsList,'answer_sheet_title' => $answerSheetTitle]);
    }

    public function answerAction(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '网络异常']);

        $answerSheetId = !is_null($request->get('answer_sheet_id')) ? $request->get('answer_sheet_id') : 0;
        $questionId    = !is_null($request->get('question_id')) ? $request->get('question_id') : 0;
        $answer        = !is_null($request->get('answer')) ? $request->get('answer') : '';

        /** @var AnswerSheet $answerSheet */
        $answerSheet = AnswerSheet::whereId($answerSheetId)->whereStatus(1)->first();
        if(!$answerSheet)
            return response()->json(['level' => 'error','message' => '答卷不存在']);

        if(strtotime($answerSheet->start_time) > time())
            return response()->json(['level' => 'error','message' => '答题还未开始']);

        if(strtotime($answerSheet->end_time) <= time())
            return response()->json(['level' => 'error','message' => '答卷已结束']);

        if($answerSheet->sort == 2){
            /** @var AnswerSheet $answerSheetOne */
            $answerSheetOne = AnswerSheet::whereSort(1)->whereStatus(1)->first();
            if(!$answerSheetOne)
                return response()->json(['level' => 'error','message' => '第一轮答卷不存在']);

            $UserAnswerOne = UserAnswer::whereAsId($answerSheetOne->id)->whereStatus(2)->orderBy('score','desc')->orderBy('submit_time','asc')->take(30)->pluck('user_id')->toArray();
            if(!in_array($user->id,$UserAnswerOne))
                return response()->json(['level' => 'error','message' => '您已被淘汰']);
        }

        /** @var Questions $question */
        $question = Questions::whereId($questionId)->whereAsId($answerSheet->id)->whereStatus(1)->first();
        if(!$question)
            return response()->json(['level' => 'error','message' => '题目不存在']);

        if($answer == '')
            return response()->json(['level' => 'error','message' => '清输入答案']);

        $userAnswer = UserAnswer::whereAsId($answerSheetId)->whereUserId($user->id)->first();
        if(!$userAnswer){
            $userAnswer = new UserAnswer();
            $userAnswer->user_id        = $user->id;
            $userAnswer->as_id          = $answerSheet->id;
            $userAnswer->save();
        }

        /** @var UserAnswerDetail $userAnswerDetail */
        $userAnswerDetail = UserAnswerDetail::whereQId($question->id)->whereUaId($userAnswer->id)->first();
        if(!$userAnswerDetail)
            $userAnswerDetail = new UserAnswerDetail();

        $userAnswerDetail->ua_id      = $userAnswer->id;
        $userAnswerDetail->q_id       = $question->id;
        $userAnswerDetail->answer     = $answer;
        $userAnswerDetail->save();

        return response()->json(['level' => 'success','message' => '保存成功','data' => $userAnswerDetail]);
    }

    public function submitAnswer(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '网络异常']);

        $answerSheetId = !is_null($request->get('answer_sheet_id')) ? $request->get('answer_sheet_id') : 0;

        /** @var AnswerSheet $answerSheet */
        $answerSheet = AnswerSheet::whereId($answerSheetId)->whereStatus(1)->first();
        if(!$answerSheet)
            return response()->json(['level' => 'error','message' => '答卷不存在']);

        if(strtotime($answerSheet->start_time) > time())
            return response()->json(['level' => 'error','message' => '答题还未开始']);

        /** @var UserAnswer $userAnswer */
        $userAnswer = UserAnswer::whereAsId($answerSheet->id)->whereUserId($user->id)->first();
        if($userAnswer){
            $userAnswer->status = 1;
            $userAnswer->submit_time = date("Y-m-d H:i:s",time());
            $userAnswer->save();
        }

        return response()->json(['level' => 'success','message' => '答卷提交成功','data' => $userAnswer]);
    }

    public function getLeaderBoard(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 1;
        $page        = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit       = !is_null($request->get('limit')) ? $request->get('limit') : 30;

        $arr = [
            'page' => $page,
            'limit' => $limit
        ];

        /** @var AnswerSheet $answerSheetTwo */
        $answerSheetTwo = AnswerSheet::whereActivityId($activityId)->whereSort(2)->whereStatus(1)->first();

        /** @var AnswerSheet $answerSheetOne */
        $answerSheetOne = AnswerSheet::whereActivityId($activityId)->whereSort(1)->whereStatus(1)->first();

        $userData = [];
        $data = [];
        if($answerSheetTwo && $answerSheetOne){
            if(strtotime($answerSheetOne->end_time) <= time() && strtotime($answerSheetTwo->end_time) > time()){
                $rank = 0;

                /** @var UserAnswer $userAnswerOne */
                $userAnswerOneList = UserAnswer::whereAsId($answerSheetOne->id)->whereStatus(2);

                $arr['total'] = $userAnswerOneList->count();

                $userAnswerOneList = $userAnswerOneList->orderBy('score','desc')->orderBy('submit_time','asc')->offset($limit * ($page - 1))->limit($limit)->get();
                if(count($userAnswerOneList) > 0){
                    foreach($userAnswerOneList as $userAnswerOne){
                        if($page > 1 && (($page - 1) * $limit + 1) > $rank){
                            $rank = ($page - 1) * $limit;
                        }

                        $rank += 1;


                        $userAnswerOne->phone = '';
                        $userAnswerOne->realname = '';
                        $userAnswerOne->photo_url = '';
                        $userAnswerOne->rank = $rank;

                        if($user){
                            if($user->id == $userAnswerOne->user_id){
                                $userData = ['user_score' => $userAnswerOne->score,'rank' => $rank];
                            }
                        }


                        /** @var User $thisUser */
                        $thisUser = User::whereId($userAnswerOne->user_id)->first();
                        if($thisUser){
                            $userAnswerOne->phone = $thisUser->phone;
                        }

                        /** @var UserInfo $thisUserInfo */
                        $thisUserInfo = UserInfo::whereUserId($userAnswerOne->user_id)->first();
                        if($thisUserInfo){
                            $userAnswerOne->realname = $thisUserInfo->realname;
                            $userAnswerOne->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                        }
                    }
                }

                $data = $userAnswerOneList;
                $arr['sort'] = 1;

            }elseif(strtotime($answerSheetTwo->end_time) <= time()){
                $userAnswerTwoUserIds = [];
                $rank = 0;

                /** @var UserAnswer $userAnswerTwo */
                $userAnswerTwoList = UserAnswer::whereAsId($answerSheetTwo->id)->whereStatus(2)->orderBy('score','desc')->orderBy('submit_time','asc')->take(30)->get();
                if(count($userAnswerTwoList) > 0){
                    foreach($userAnswerTwoList as $userAnswerTwo){
                        $rank += 1;

                        $userAnswerTwo->phone = '';
                        $userAnswerTwo->realname = '';
                        $userAnswerTwo->photo_url = '';
                        $userAnswerTwo->rank = $rank;

                        if($user){
                            if($user->id == $userAnswerTwo->user_id){
                                $userData = ['user_score' => $userAnswerTwo->score,'rank' => $rank];
                            }
                        }


                        /** @var User $thisUser */
                        $thisUser = User::whereId($userAnswerTwo->user_id)->first();
                        if($thisUser){
                            $userAnswerTwo->phone = $thisUser->phone;
                        }

                        /** @var UserInfo $thisUserInfo */
                        $thisUserInfo = UserInfo::whereUserId($userAnswerTwo->user_id)->first();
                        if($thisUserInfo){
                            $userAnswerTwo->realname = $thisUserInfo->realname;
                            $userAnswerTwo->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                        }

                        array_push($userAnswerTwoUserIds,$userAnswerTwo->user_id);
                    }
                }

                if($page == 1){
                    $data =  $userAnswerTwoList;

                    /** @var UserAnswer $userAnswerOne */
                    $userAnswerOneList = UserAnswer::whereNotIn('user_id',$userAnswerTwoUserIds)->whereStatus(2)->whereAsId($answerSheetOne->id);

                    $total = $userAnswerOneList->count();
                }elseif($page > 1){
                    $page = $page - 1;

                    /** @var UserAnswer $userAnswerOne */
                    $userAnswerOneList = UserAnswer::whereNotIn('user_id',$userAnswerTwoUserIds)->whereStatus(2)->whereAsId($answerSheetOne->id);

                    $total = $userAnswerOneList->count();

                    $userAnswerOneList = $userAnswerOneList->orderBy('score','desc')->orderBy('submit_time','asc')->offset($limit * ($page - 1))->limit($limit)->get();
                    if(count($userAnswerOneList) > 0){
                        foreach($userAnswerOneList as $userAnswerOne){
                            if(($page * $limit + 1) > $rank){
                                $rank = $page * $limit;
                            }

                            $rank += 1;

                            $userAnswerOne->phone = '';
                            $userAnswerOne->realname = '';
                            $userAnswerOne->photo_url = '';
                            $userAnswerOne->rank = $rank;

                            /** @var User $thisUser */
                            $thisUser = User::whereId($userAnswerOne->user_id)->first();
                            if($thisUser){
                                $userAnswerOne->phone = $thisUser->phone;
                            }

                            /** @var UserInfo $thisUserInfo */
                            $thisUserInfo = UserInfo::whereUserId($userAnswerOne->user_id)->first();
                            if($thisUserInfo){
                                $userAnswerOne->realname = $thisUserInfo->realname;
                                $userAnswerOne->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                            }
                        }
                    }

                    $data = $userAnswerOneList;
                }




                $arr['sort'] = 2;

                $arr['total'] = 30 + $total;
            }
        }


        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'user_data' => $userData,'page_info' => $arr]);
    }
}
